package imagecutter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author faila
 */
public class Configuration {
    //This are required properties in configuration file.

    public static final String HEIGHT = "height";
    public static final String WIDTH = "width";
    public static final String COUNT_SAVED_IMAGES = "countSaveImages";
    Properties properties = new Properties();

    /**
     * Load properties from file and checks if all properties are present.
     * @param configurationFilepath Path to configuration file.
     * @throws RuntimeException thrown when problems with properties loading
     */
    public void loadPropertiesFile(String configurationFilepath) throws RuntimeException {
        boolean fileExist = Utils.checkFile(configurationFilepath);

        if (!fileExist) {
            throw new IllegalArgumentException("File (" + configurationFilepath + ") doesn't exist or is not a file");
        }

        Exception fileLoadException = loadFile(configurationFilepath);
        if (fileLoadException != null) {
            throw new RuntimeException("Problem while loading file: " + fileLoadException.getMessage(), fileLoadException);
        }

        boolean isPropertiesChecked = checkAllProperties();
        if (!isPropertiesChecked) {
            throw new RuntimeException("Missing properties in configuration file.");
        }

    }

    private boolean checkFile(String path) {
        File file = new File(path);
        return file.exists() && file.isFile();
    }

    private Exception loadFile(String path) {
        Exception fileLoadedException = null;
        try {
            properties.load(new FileInputStream(path));
        } catch (IOException e) {
            fileLoadedException = e;
        }
        return fileLoadedException;
    }

    private boolean checkAllProperties() {
        boolean isAllPropertiesPresent = true;
        if (properties.getProperty(COUNT_SAVED_IMAGES) == null || properties.getProperty(HEIGHT) == null || properties.getProperty(WIDTH) == null) {
            isAllPropertiesPresent = false;
        }
        return isAllPropertiesPresent;
    }

    /**
     * Returns a property as String.
     * Call example: conf.getPropertyAsString(Configuration.COUNT_SAVED_IMAGES)
     * @param propertyKey
     * @return property as String
     */
    public String getPropertyAsString(String propertyKey) {
        return properties.getProperty(propertyKey);
    }

    /**
     * Returns a property as Integer.
     * Call example: conf.getPropertyAsInteger(Configuration.COUNT_SAVED_IMAGES)
     * @param propertyKey
     * @return property as int
     */
    public int getPropertyAsInteger(String propertyKey) {
        return Integer.parseInt(properties.getProperty(propertyKey));
    }
}
